<?php

namespace App\Models\Admin;

use App\Models\Base;

class AdminUser extends Base
{

    const LOGIN_KEY = 'admin:login:';
    const INFO_KEY = 'admin:info:';

    /**
     * @var string $tableName 指定表名
     */
    protected $tableName = 'es_admin_user';
    protected $autoTimeStamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 列表返回字段
    protected static $listField = 'id, account, username, head_pic, sex, role_id, status, last_login_time, create_time, update_time';

    /**
     * 获取授权信息
     */
    public function getAuthUserInfo($token) : ?array
    {
        $redis = self::redis();
        if (!($uid = $redis -> get(self::LOGIN_KEY.$token))) return null;
        return $this->getInfoForUid($uid);
    }

    /**
     * 获取后台用户信息
     */
    public function getInfoForUid($uid) : ?array
    {
        $redis = self::redis();
        if (($infoJSON = $redis -> get(self::INFO_KEY.$uid)) && $info = json_decode($infoJSON, true)) return $info;
        $info = self::create() -> alias('au')
            -> field('au.*, ar.role_name, ar.menu_ids')
            -> join('es_admin_role ar', 'au.role_id = ar.id', 'LEFT') 
            -> where(['au.id' => $uid]) -> get();
        if (!$info = $info->lastQueryResult()->getResult()[0] ?? '') return null;
        $redis -> set(self::INFO_KEY.$uid, json_encode($info));
        return $info; 
    }

    /**
     * 用户验证登录
     */
    public function signAndBackUserInfo($account, $password) : ? array
    {
        $result = self::create() -> where(['account' => $account]) -> get();
        if (!$result) return null;
        $result = $result -> toArray();
        if (!$result || !(password_verify($password, $result['password']))) return null;
        unset($result['password']);
        $token = md5(mt_rand(1000, 9999).time());
        $redis = self::redis();
        $redis -> set(self::LOGIN_KEY.$token, $result['id'] ?? 0, 3600*24*7);
        return ['token' => $token, 'user_info' => $result]; 
    }


}